package main

import (
	"fmt"
	"strconv"
)

/*
类型断言
https://tour.go-zh.org/methods/15

*/
func main() {
	//fmt.Println("----DemoTourTypeAssertion---")
	//DemoTourTypeAssertion()
	fmt.Println("----DemoTypeAssertion2---")
	DemoTypeAssertion2()
}
func DemoTourTypeAssertion() {
	var i interface{} = "hello"

	s := i.(string)
	fmt.Println(s)

	s, ok := i.(string)
	fmt.Println(s, ok)

	f, ok := i.(float64)
	fmt.Println(f, ok)

	f = i.(float64) // 报错(panic)
	fmt.Println(f)
}

type Element interface{}
type List []Element

type Person struct {
	name string
	age  int
}

//打印
func (p Person) String() string {
	return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}

func DemoTypeAssertion2() {
	list := make(List, 3)
	list[0] = 1       //an int
	list[1] = "Hello" //a string
	list[2] = Person{"Dennis", 70}

	for index, element := range list {
		switch value := element.(type) {
		case int:
			fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
		case string:
			fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
		case Person:
			fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
		default:
			fmt.Println("list[%d] is of a different type", index)
		}
	}
}
